package xin.zhiyin.服务.书.实现;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.zhiyin.仓库.书.书章节Repository;
import xin.zhiyin.实体.书Entity;
import xin.zhiyin.仓库.书.书Repository;
import xin.zhiyin.实体.书章节Entity;
import xin.zhiyin.服务.书.书Service;
import xin.zhiyin.服务.书.书章节Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional(rollbackFor = Exception.class) /*声明式事务管理*/
public class 书Service实现 implements 书Service {
    @Autowired
    private 书Repository 书Dao;
    @Autowired
    private 书章节Service 章节Service;
    @Autowired
    private 书章节Repository 章节Repository;
    @Override
    public void 保存(书Entity 书) {
        书Dao.save(书);

    }
    @Override
    public 书Entity 根据Id获取书(Long id) {
        书Entity b = new 书Entity();
        Optional<书Entity> 书 =  书Dao.findById(id);
        if(书.isPresent())
        {
            b = 书.get();
        }
        return b;
    }
    @Override
    public List<书Entity> 获取所有书() {
        return 书Dao.findAll();
    }

    @Override
    public List<书Entity> 根据categoryId获取书(Long categoryId) {
        return 书Dao.findByCategoryId(categoryId);
    }

    @Override
    public List<书Entity> 获取所有书(Example<书Entity> example) {
        return 书Dao.findAll(example);
    }

    @Override
    public Page<书Entity> 分页查询(书Entity 书, Pageable pageable) {
        Example<书Entity> example = Example.of(书);
        return 书Dao.findAll(example,pageable);
    }


    @Override
    public void 更新(书Entity 书) {
        书Entity shu = 书Dao.findById(书.getId()).get();
        BeanUtils.copyProperties(书, shu);
        书Dao.save(shu);
    }

    @Override
    public void 批量删除(List bookIds) {

        for(int i=0;i<bookIds.size();i++)
        {
            List<Long> 章节Ids = new ArrayList();
            List<书章节Entity> 章节列表 = 章节Service.根据BookId获取书章节((Long) bookIds.get(i));
            for(int j=0;j<章节列表.size();j++)
            {
                章节Ids.add(章节列表.get(j).getId());
            }
            章节Service.批量删除(章节Ids);
        }
        书Dao.批量删除(bookIds);
    }


}
